package com.c3po.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.c3po.bean.User;
import com.c3po.utils.C3P0Util;


public class DaoImpl implements Dao{
	private QueryRunner queryRunner = new QueryRunner();
	private Connection conn = null;
	@Override
	public int save(User user) {
		int k=-1;
		Object[] params=new Object[]{user.getUsername(),user.getPassword()};
		String sql="insert  into user (username,password) values(?,?)";
		try {
			conn = C3P0Util.getConnection();
			conn.setAutoCommit(false);
			k=queryRunner.update(conn, sql, params);
			conn.commit();
		} catch (Exception e) {
			System.out.println(e);
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e1) {
			}
		} finally {
			C3P0Util.close(conn, null, null);
		}
		return k;
	}

	@Override
	public List<User> select(String username) {
		List<User> list=null;
		Object[] params=new Object[]{username};
		String sql="select username,password from user where username=?";
		try {
			System.out.println("11111111111");
			conn = C3P0Util.getConnection();
			conn.setAutoCommit(false);
			list = queryRunner.query(conn, sql, new BeanListHandler<User>(User.class),params);
			conn.commit();
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e1) {
			}
		} finally {
			C3P0Util.close(conn, null, null);
		}
		return list;
	}

}
